import logging
import sys
from pathlib import Path
from datetime import datetime
from pytz import timezone
from logging.handlers import TimedRotatingFileHandler

root_path = Path(__file__).parents[2]  # 项目根目录

# 时区
tz = timezone('Asia/Shanghai')

def timetz(*args):
    return datetime.now(tz).timetuple()

# === 1. 初始化通用日志系统（只调用一次！）===
def init_main_logger(
    enable_console: bool = False,
) -> logging.Logger:
    """
    初始化主日志系统（包含全局异常钩子），应只在程序入口调用一次。
    """
    log_path = root_path / "logs" / "App.log"

    # 自定义时间格式（带时区）
    logging.Formatter.converter = timetz
    formatter = logging.Formatter(
        fmt="%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S"
    )

    file_handler = TimedRotatingFileHandler(
        filename=str(log_path),
        when="midnight",
        interval=1,
        backupCount=15,
        encoding="utf-8"
    )
    file_handler.suffix = "%Y-%m-%d"
    file_handler.setFormatter(formatter)

    handlers = [file_handler]
    if enable_console:
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setFormatter(formatter)
        handlers.append(console_handler)

    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)

    if not root_logger.handlers:
        for h in handlers:
            root_logger.addHandler(h)

    # 全局异常钩子
    def handle_unhandled_exception(exc_type, exc_value, exc_traceback):
        if issubclass(exc_type, KeyboardInterrupt):
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            return
        root_logger.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))

    sys.excepthook = handle_unhandled_exception
    return root_logger


# === 2. 获取通用 logger（任意模块使用）===
def get_logger(name: str = __name__) -> logging.Logger:
    """获取结构化日志 logger"""
    return logging.getLogger(name)


# === 3. 获取 JSON logger（任意模块使用）===
def get_json_logger() -> logging.Logger:
    """获取纯 JSON 格式日志 logger"""
    logger_name = "json_logger"
    logger = logging.getLogger(logger_name)

    # 避免重复添加 handler
    if not logger.handlers:
        log_path = root_path / "logs" / "json.log"
        log_path.parent.mkdir(parents=True, exist_ok=True)

        handler = TimedRotatingFileHandler(
            filename=str(log_path),
            when="midnight",
            interval=1,
            backupCount=7,
            encoding="utf-8"
        )
        handler.suffix = "%Y-%m-%d"
        handler.setFormatter(logging.Formatter("%(message)s"))
        logger.addHandler(handler)
        logger.setLevel(logging.INFO)
        logger.propagate = False  # 避免 JSON 日志也输出到主日志

    return logger


# 如果直接运行 log.py，测试日志功能
if __name__ == "__main__":
    init_main_logger(enable_console=True)
    logger = get_logger("test")
    logger.info("This is a test log message.")
    try:
        1 / 0
    except Exception:
        logger.exception("An error occurred")